import { useState, useEffect } from 'react';
import { getDictDataEnabledByTypeCode, DictData } from 'src/api/dict-api';

// 字典数据缓存
const dictCache = new Map<string, DictData[]>();

export function useDict(typeCode: string) {
  const [data, setData] = useState<DictData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadDictData = async () => {
      // 如果缓存中有数据，直接使用
      if (dictCache.has(typeCode)) {
        setData(dictCache.get(typeCode)!);
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const response = await getDictDataEnabledByTypeCode(typeCode);
        if (response.success) {
          const dictData = response.data;
          setData(dictData);
          // 缓存数据
          dictCache.set(typeCode, dictData);
        } else {
          setError('加载字典数据失败');
        }
      } catch (err) {
        setError('加载字典数据失败');
      } finally {
        setLoading(false);
      }
    };

    if (typeCode) {
      loadDictData();
    }
  }, [typeCode]);

  // 清除缓存的方法
  const clearCache = () => {
    dictCache.delete(typeCode);
  };

  // 刷新数据的方法
  const refresh = () => {
    clearCache();
    setData([]);
    setError(null);
    setLoading(false);
  };

  return {
    data,
    loading,
    error,
    clearCache,
    refresh,
  };
}

// 预定义的字典类型
export const DICT_TYPES = {
  PAYMENT_WAY: 'PAYMENT_WAY',
  INCOME_SOURCE: 'INCOME_SOURCE',
  BILL_TYPE: 'BILL_TYPE',
  PAYMENT_PLATFORM: 'PAYMENT_PLATFORM',
} as const;

// 便捷的Hook
export function usePaymentWays() {
  return useDict(DICT_TYPES.PAYMENT_WAY);
}

export function useIncomeSources() {
  return useDict(DICT_TYPES.INCOME_SOURCE);
}

export function useBillTypes() {
  return useDict(DICT_TYPES.BILL_TYPE);
}

export function usePaymentPlatforms() {
  return useDict(DICT_TYPES.PAYMENT_PLATFORM);
}
